'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }

  //新增
  async put(){
    let {ctx,service} = this;
    let {title,status,important} = ctx.request.body;
    if(title && status && important){
        let timer = new Date();
        let author = 'sum';
        let readnum = Math.ceil(Math.random() * 100);
        try{
            // createtime,title,author,important,readnum,status
            await service.home.put(timer,title,author,important,readnum,status);
            ctx.body = {
                code:1,
                msg:'添加成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'缺少参数'
        }
    }
  }

  //修改
  async update(){
    let {ctx,service} = this;
    let {title,status,important,id} = ctx.request.body;
    if(title && status && important && id){
        let timer = new Date();
        let author = 'sum';
        let readnum = Math.ceil(Math.random() * 100);
        //修改
        try{
            await service.home.update(timer,title,author,important,readnum,status,id);
            ctx.body = {
                code:1,
                msg:'修改成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'缺少参数'
        }
    }
  }

  //删除
  async del(){
      let {ctx,service} = this;
      let {id} = ctx.query;
      if(id){
        try{
            await service.home.del(id);
            ctx.body = {
                code:1,
                msg:'删除成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
      }else{
        ctx.body = {
            code:2,
            msg:'缺少参数'
        }
      }
  }

  //查询
  async bookslist(){
      let {ctx,service} = this;
      let {start=0,limit=8} = ctx.query;  //起始下标 前端算

      try{
        let data = await service.home.bookslist(start,limit);
        let total = await service.home.total();
        ctx.body = {
            code:1,
            data,
            total:total[0]['count(*)']
        }
      }catch(e){
        ctx.body = {
            code:0,
            msg:e
        }  
      }
    }
}

module.exports = HomeController;
